package com.mrjy.integral.bo;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.HappinessInfo;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.SignInInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.dao.ISignInInfoDao;
import com.mrjy.integral.util.HappinessInfoEnum;
import com.mrjy.integral.util.HappinessInfoUtil;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;

@Service("signInInfoBo")
public class SignInInfoBo implements ISignInInfoBo{
	
	@Resource
	private ISignInInfoDao signInInfoDao;
	
	@Resource
	private IHappinessInfoDao happinessInfoDao ;

	@Override
	public Object txInsert(SignInInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		info.setLastModifyTime(new Timestamp(System.currentTimeMillis()));
		info.setDisableFlag(0);
		
		int count = signInInfoDao.insert(info);
		if(count == 1){
			map.put("err_code", 0);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "插入失败")	;
		}
		return map ;
		
	}
	@Override
	public Object queryById(int id) {
		Map<String, Object> map = new HashMap<String,Object>();
		SignInInfo info = signInInfoDao.queryById(id);
		if(info != null){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", info);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
		}
		return map;
	}
	@Override
	public Object txUpdateById(SignInInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(info.getText()) && StringUtils.isBlank(info.getPicName())) {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        }

		int count = signInInfoDao.updateById(info);
		if(count == 1){
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败")	;
		}
		return map ;
	}
	@Override
	public int deleteByIds(int[] ids) {
		try{
			return signInInfoDao.deleteByIds(ids);
		}catch(DataAccessException  e){
			return 0;
		}
	}
	@Override
	public int updateDisableFlag(SignInInfo info) {
		return signInInfoDao.updateDisableFlag(info);
	}
	@Override
	public Object signIn(SignInInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(info.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map ;
		}
		SignInInfo existInfo = signInInfoDao.queryByUserId(info.getUserId());
		if(existInfo == null){
			info.setContinuitySignCount(1);
			info.setCumulationSignCount(1);
			info.setDisableFlag(0);
			info.setLastModifyTime(new Timestamp(System.currentTimeMillis()));
			
			int count = signInInfoDao.insert(info);
			if(count == 1){
				//积分添加
				IntegralInfo intetral = IntegralUtil.setIntegral(info.getUserId()
						, IntegralUtil.getScoreBySignInDay(1)
						, "第1天签到", IntegralEnum.SIGN_IN.getTypeId(), info.getId());
				
				//爱值添加
				HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(info.getUserId()
						, IntegralUtil.getScoreBySignInDay(1), "第1天签到"
						, HappinessInfoEnum.SIGN_IN.getTypeId(), "0", info.getId());
				happinessInfoDao.insert(hi);
				
				map.put("err_code", 200);
				map.put("err_msg", "首次签到成功");
                map.put("score", intetral.getScore());
                map.put("conti_day", 1);
				return map ;
			}else {
				map.put("err_code", 100);
				map.put("err_msg", "首次签到失败");
				map.put("score", null);
				map.put("conti_day", null);
				return map ;
			}
		}else{
			if(existInfo.getLastModifyTime() != null){
				if(DateUtil.isSameDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
					map.put("err_code", 100);
					map.put("err_msg", "当天已经签到");
					return map ;
				}else{
					//是否连续签到
					if(DateUtil.isBeforDay(existInfo.getLastModifyTime().getTime(), System.currentTimeMillis())){
						existInfo.setLastModifyTime(new Timestamp(System.currentTimeMillis()));
						existInfo.setContinuitySignCount(existInfo.getContinuitySignCount()+1);
						existInfo.setCumulationSignCount(existInfo.getCumulationSignCount()+1);
						int count = signInInfoDao.updateById(existInfo);
						if(count == 1){//判断续签几天，添加相应的积分
							int contiDay = existInfo.getContinuitySignCount();
							//积分添加
							IntegralInfo intetral = IntegralUtil.setIntegral(existInfo.getUserId()
                                    , IntegralUtil.getScoreBySignInDay(contiDay >= 6 ? 6 : contiDay)
                                    , "第"+contiDay+"天签到", IntegralEnum.SIGN_IN.getTypeId(), existInfo.getId());
							
							//爱值添加
							HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(existInfo.getUserId()
                                    , IntegralUtil.getScoreBySignInDay(contiDay >= 6 ? 6 : contiDay)
                                    , "第"+contiDay+"天签到", HappinessInfoEnum.SIGN_IN.getTypeId()
									, "0", existInfo.getId());
							happinessInfoDao.insert(hi);
							
							map.put("err_code", 200);
							map.put("err_msg", "第"+existInfo.getContinuitySignCount()+"天签到成功");
                            map.put("score", intetral.getScore());
                            map.put("conti_day", contiDay);
							return map ;
						}
					}else{//断签
						existInfo.setLastModifyTime(new Timestamp(System.currentTimeMillis()));
						existInfo.setContinuitySignCount(1);
						existInfo.setCumulationSignCount(existInfo.getCumulationSignCount()+1);
						int count = signInInfoDao.updateById(existInfo);
						if(count == 1){
							//积分添加
							IntegralInfo intetral = IntegralUtil.setIntegral(existInfo.getUserId()
									, IntegralUtil.getScoreBySignInDay(1)
									, "第1天签到", IntegralEnum.SIGN_IN.getTypeId(), existInfo.getId());
							
							//爱值添加
							HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(existInfo.getUserId()
									, IntegralUtil.getScoreBySignInDay(1), "第1天签到"
									, HappinessInfoEnum.SIGN_IN.getTypeId(), "0", existInfo.getId());
							happinessInfoDao.insert(hi);
							
							map.put("err_code", 200);
							map.put("err_msg", "断签后第1天签到成功");
                            map.put("score", intetral.getScore());
                            map.put("conti_day", 1);
							return map ;
						}
					}
				}
			}
		}
		return map;
	}


    @Override
    public Object queryByUserId(int userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        SignInInfo info = signInInfoDao.queryByUserId(userId);
        if (info != null) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("info", info);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
        }
        return map;
    }


    @Override
    public Object updateByUserId(SignInInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(info.getText()) && StringUtils.isBlank(info.getPicName())) {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        }

        int count = signInInfoDao.updateByUserId(info);
        if (count == 1) {
            map.put("err_code", 0);
            map.put("err_msg", "更新成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "更新失败");
        }
        return map;
    }

}
